local redis = require "resty.redis_iresty"
local json = require 'cjson'


--获取客户端ip
function get_client_ip()
    local headers=ngx.req.get_headers()
    local ip=headers["X-REAL-IP"] or headers["X_FORWARDED_FOR"] or ngx.var.remote_addr or "0.0.0.0"
    return ip
end


local args = ngx.req.get_uri_args()
--local args = ngx.req.get_post_args()

local openid = args.openid 
if not openid then 
     local msg = {code=2, 
              msg="no openid, input error"}
  	ngx.say(json.encode(msg))
	return 
end 

local name = args.name or "游客"
local url = args.url or ""

local ip = get_client_ip()
local sex = args.sex or 1
local my_redis = redis:new()
local pid = my_redis:hget("openid_pid", openid)
ngx.log(ngx.ERR, string.format("1111111111111pid:%s ", pid, openid ))
if not pid then
  pid = my_redis:incr("player_cnt") + 100000
  my_redis:hmset("player:"..pid,"pid",pid,"name",name,"openid",openid,"url",url,"ip",ip,"fangka",3,"money",0,"room",0,"creatTime",os.date("%Y-%m-%d %H:%M:%S", os.time()),"sortKey",os.time(),"sex",sex)
  my_redis:hset("openid_pid", openid, pid)
end

my_redis:hmset("player:"..pid,"ip",ip,"loginTime",os.date("%Y-%m-%d %H:%M:%S", os.time()),"name",name)

local res, err  = my_redis:hmget("player:"..pid,"fangka","money", "room", "pid", "askMa", "sex" )

fangka = res[1]
money = res[2]
room = res[3]
pid = res[4]
askMa = res[5]
sex = res[6]


ngx.log(ngx.ERR, string.format("fangka:%s, money:%s, room:%s, pid:%s, askMa:%s, sex :%s ", res[1],res[2],res[3],res[4],res[5],res[6] ))

if tonumber(room) == 0  then 
    msg = {fangka = fangka,money = money,pid = pid, askMa = askMa, sex = sex}
    msg.code =0
    msg.desc = "success"
else
	local ip = my_redis:hget("room:"..room,"ip")
	local port = my_redis:hget("room:"..room,"port")

	msg = {fangka = fangka,money = money,pid = pid,ip = ip,room = room,ip = ip,port = port, askMa = askMa, sex = sex}
    msg.code =0
    msg.desc = "success"
	
end

math.randomseed(tostring(os.time()):reverse():sub(1, 7)) --设置随即种子
local token = "token:"..openid..os.time().. math.random(1,1000000)

local token_value = {pid=pid, name=name, openid=openid}
my_redis:set(token, json.encode(token_value))
my_redis:expire(token, 30) --token30秒内有效


msg.ip = "127.0.0.1"
msg.port = "3000"
msg.token = token


ngx.say(json.encode(msg))
























 
